package com.kuang.controller;

import com.kuang.utils.RedisUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 测试分布式锁
 */
@RestController
public class TestController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedissonClient redissonClient;

    @PostMapping("/shop/{pid}")
    public void lock(@PathVariable String pid){
        //        根据参数创建锁实例
        RLock lock = redissonClient.getLock("lock:" + pid);
        try{
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"进入锁---------------");
            // 测试锁是否生效的数字加减
            if (!redisUtil.hasKey("incr")){
                redisUtil.incr("incr",1);
            }else if (Integer.parseInt(redisUtil.get("incr").toString())==0){
                long incr = redisUtil.incr("incr", 1);
            }else {
                redisUtil.decr("incr",1);
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }finally {
            if(lock.isLocked()){//判断锁是否处于锁定
                if(lock.isHeldByCurrentThread()){//判断是否时该进程自己的锁
                    lock.unlock();
                }
            }
        }
    }
}
